<template>
  <view class="form-content">
    <u-form
      :model="form"
      ref="refForm"
      label-position="top"
      :error-type="['toast']"
    >
      <u-form-item label="名称" prop="expName" :required="true">
        <view class="white-bg">
          <u-input v-model="form.expName" />
        </view>
      </u-form-item>
      <u-form-item label="附件" prop="fileList">
        <view class="card-width">
          <updateFileVue v-model="form.fileList"></updateFileVue>
        </view>
      </u-form-item>
    </u-form>
  </view>
</template>
<script lang="ts" setup>
import { onReady } from '@dcloudio/uni-app';
import updateFileVue from '@/components/updateFile.vue';

const props = withDefaults(
  defineProps<{
    form: any;
  }>(),
  {
    form: {
      expName: '',
      fileList: undefined,
    },
  }
);

const form = ref<any>({});

watch(
  () => props.form,
  (nVal) => {
    form.value = nVal;
  },
  {
    deep: true,
  }
);

const refForm = ref();
const rules = {
  expName: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur,change',
    },
  ],
};

const getData = () => {
  return new Promise((resolve, reject) => {
    refForm.value.validate((valid: boolean) => {
      if (valid) {
        if (form.value.fileList && form.value.fileList.length) {
          form.value.fileList.forEach((item: any) => {
            item.platformFileId = item.uid;
            item.fileName = item.name;
            const arr = item.name.split('.');
            item.fileType == arr[arr.length - 1].toLocaleLowerCase();
          });
        }
        return resolve(form.value);
      } else {
        return reject(false);
      }
    });
  });
};

onReady(() => {
  refForm.value.setRules(rules);
});

defineExpose({
  getData,
});
</script>
<style lang="scss">
.form-content {
  padding: 32rpx;
  .white-bg {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 0 20rpx;
  }
  .card-width {
    width: calc(100vw - 64rpx);
  }
}
</style>
